﻿#include "uplugininfo.h"
#include "uiplugin.h"

#include <QPluginLoader>

class UPluginInfoPrivate
{
    Q_DECLARE_PUBLIC(UPluginInfo)
public:
    UPluginInfoPrivate(UPluginInfo* parent) : q_ptr(parent) {}
    ~UPluginInfoPrivate() {}

    UPluginInfo* q_ptr = nullptr;
    QPluginLoader loader;
    UIPlugin* plugin = nullptr;
    bool isError = false;
};

UPluginInfo::UPluginInfo(QObject* parent) : QObject(parent)
    , d_ptr(new UPluginInfoPrivate(this))
{
}

UPluginInfo::~UPluginInfo()
{
}

bool UPluginInfo::loadLibrary()
{
    Q_D(UPluginInfo);
    if (d->loader.load()) {
        d->plugin = qobject_cast<UIPlugin*>(d->loader.instance());
        if (nullptr == d->plugin) {
            qCritical() << "loadLibrary object is not UIPlugin!!!";
            d->isError = true;
            return false;
        } else {
            qInfo() << d->loader.fileName() << "load success!!!";
            d->isError = false;
            return true;
        }
    } else {
        qCritical() << "loadLibrary failed, name:" << d->loader.fileName() << "error:" << d->loader.errorString();
        d->isError = true;
        return false;
    }
}

bool UPluginInfo::read(const QString &file)
{
    Q_D(UPluginInfo);
    d->loader.setFileName(file);
    return true;
}

UIPlugin* UPluginInfo::iPlugin()
{
    Q_D(UPluginInfo);
    return d->plugin;
}

QString UPluginInfo::iPluginName()
{
    Q_D(UPluginInfo);
    return d->loader.fileName();
}

bool UPluginInfo::isError()
{
    Q_D(UPluginInfo);
    return d->isError;
}

bool UPluginInfo::unload()
{
    Q_D(UPluginInfo);
    return d->loader.unload();
}

QJsonObject UPluginInfo::pluginInfo() const
{
    Q_D(const UPluginInfo);
    return d->loader.metaData();
}


